<template>
  <el-dialog
    :title="dialist.isAdd ? '添加商品分类' : '编辑商品分类'"
    :visible.sync="dialist.isShow"
    center
    :before-close="cancle"
    @opened="opened"
  >
    <el-form :model="list" ref="diaform" :rules="rules">
      <el-form-item
        :label-width="formLabelWidth"
        label="一级分类"
        prop="first_cateid"
      >
        <el-select
          v-model="list.first_cateid"
          @change="menuChange(list.first_cateid, false)"
        >
          <el-option
            :value="item.id"
            v-for="item in firstarr"
            :key="item.id"
            :label="item.catename"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        :label-width="formLabelWidth"
        label="二级分类"
        prop="second_cateid"
      >
        <el-select v-model="list.second_cateid">
          <el-option
            :value="item.id"
            v-for="item in secondarr"
            :key="item.id"
            :label="item.catename"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        :label-width="formLabelWidth"
        label="商品名称"
        prop="goodsname"
      >
        <el-input
          v-model="list.goodsname"
          placeholder="请输入商品名称"
        ></el-input>
      </el-form-item>
      <el-form-item :label-width="formLabelWidth" label="价格" prop="price">
        <el-input v-model="list.price" placeholder="请输入商品价格"></el-input>
      </el-form-item>
      <el-form-item
        :label-width="formLabelWidth"
        label="市场价格"
        prop="market_price"
      >
        <el-input
          v-model="list.market_price"
          placeholder="请输入市场价格"
        ></el-input>
      </el-form-item>
      <el-form-item label="图片" :label-width="formLabelWidth">
        <!-- 
          on-preview 这个是文件上传后点击触发的函数
          on-remove 这个是文件上传后点击删除 触发的函数
          action 图片上传地址，#没有上传地址
          list-type  picture-card缩略图
          auto-upload 会根据action里面的地址。自动上传
          on-change文件改变时的钩子函数，上传成功和失败都会调用
         -->
        <el-upload
          action="#"
          list-type="picture-card"
          :auto-upload="false"
          :on-change="filechange"
          :file-list="fileList"
          :on-remove="remove"
          :on-preview="preview"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <!-- 放大功能 -->
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
      </el-form-item>
      <el-form-item
        :label-width="formLabelWidth"
        label="商品规格"
        prop="specsid"
      >
        <el-select v-model="list.specsid" @change="specsChange(list.specsid,false)">
          <el-option
            :value="item.id"
            v-for="item in specsarr"
            :key="item.id"
            :label="item.specsname"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        :label-width="formLabelWidth"
        label="规格属性"
        prop="specsattr"
      >
        <el-select v-model="list.specsattr" multiple>
          <el-option
            :value="item"
            v-for="item in attrsarr"
            :key="item"
            :label="item"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="是否是新品" :label-width="formLabelWidth">
        <el-radio-group v-model="list.isnew">
          <el-radio :label="1">是</el-radio>
          <el-radio :label="2">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="是否热卖" :label-width="formLabelWidth">
        <el-radio-group v-model="list.ishot">
          <el-radio :label="1">是</el-radio>
          <el-radio :label="2">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="状态" :label-width="formLabelWidth">
        <el-switch
          v-model="list.status"
          :active-value="1"
          :inactive-value="2"
        ></el-switch>
      </el-form-item>
      <el-form-item label="商品描述" :label-width="formLabelWidth">
        <div id="wangeditor"></div>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="cancle">取 消</el-button>
      <el-button type="primary" v-if="dialist.isAdd" @click="add"
        >添 加</el-button
      >
      <el-button type="primary" v-else @click="edit">编 辑</el-button>
    </div>
  </el-dialog>
</template>

<script>
import {
  addGoods,
  getGoodsOne,
  editGoods,
  getCatelist,
  specsList,
  getSpecsOne,
} from "../../util/axios";
import E from "wangeditor";
import { mapActions, mapGetters } from "vuex";
export default {
  data() {
    return {
      list: {
        first_cateid: "",
        second_cateid: "",
        price: "",
        market_price: "",
        img: "",
        description: "",
        goodsname: "",
        specsid: "",
        specsattr: "",
        isnew: 1,
        ishot: 1,
        status: 1,
      },
      editor: null,

      //用于处理一二级分类
      firstarr: [],
      secondarr: [],
      //用于回显图片的数组 记得用完要清空
      fileList: [],
      //用于处理商品规格和商品属性
      specsarr: [],
      attrsarr: [],
      formLabelWidth: "120px",
      rules: {
        first_cateid: [
          { required: true, message: "请输入一级分类", trigger: "blur" },
        ],
        second_cateid: [
          { required: true, message: "请选择二级分类", trigger: "blur" },
        ],
        price: [{ required: true, message: "请输入价格", trigger: "blur" }],
        market_price: [
          { required: true, message: "请输入市场价格", trigger: "blur" },
        ],
        goodsname: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
          {
            min: 2,
            max: 12,
            message: "长度在3到12个字符之间",
            trigger: "blur",
          },
        ],
        specsid: [
          { required: true, message: "请选择商品规格", trigger: "blur" },
        ],
        specsattr: [
          { required: true, message: "请选择商品属性", trigger: "blur" },
        ],
      },
      // menuOption: [],
      dialogImageUrl: "",
      dialogVisible: false,
    };
  },
  computed: {
    ...mapGetters({
         menulist: "goods/getGoods"
    }),
  },
  props: ["dialist"],
  methods: {
    //弹窗打开完成后加载富文本编辑器
    opened() {
      this.editor = new E("#wangeditor");
      this.editor.create();
      this.editor.txt.html(this.list.description);
    },
    //一级菜单改变 联动二级菜单
    menuChange(id, n) {
      getCatelist({ pid: id }).then((res) => {
        //数据回显时,需要判断是都清空二级路由，如果直接清空会影响数据回显
        if (!n) {
          this.list.second_cateid = "";
        }
        this.secondarr = res.list;
      });
    },
    //规格联动属性
    specsChange(id,n) {
      getSpecsOne({ id }).then((res) => {
        if (res.code == 200) {
            if (!n) {
            this.list.specsattr = "";
        }
          this.attrsarr = res.list?res.list[0].attrs:[];
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    ...mapActions({
      //获取文件列表
      getGoodsListAction: "goods/getGoodslistACtion",
      //page改变的时候触发的行数
      change: "goods/currentChange",
      //改变total的
      getTotalAction:"goods/getGoodsCount"
    }),
    //点击取消后隐藏dialog
    cancle() {
      //隐藏dialog
      this.$emit("cancle", false);
      //清空表格
      this.list = {
        first_cateid: "",
        second_cateid: "",
        price: "",
        market_price: "",
        img: "",
        description: "",
        goodsname: "",
        specsid: "",
        specsattr: "",
        isnew: 1,
        ishot: 1,
        status: 1,
      };
      //清空验证
      this.$refs.diaform.resetFields();
      this.fileList = [];
      this.dialogImageUrl = "";
      this.dialogVisible = false;
      // this.firstarr =[];
      this.secondarr =[];
      // this.specsarr=[],
      this.attrsarr=[];
    },
    //出现图片放大预览功能
    preview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    //点击图片删除的功能
    remove() {
      this.fileList = [];
      this.list.img = "";
    },
    //添加功能
    add() {
      this.$refs.diaform.validate((val) => {
        if (val) {
          //文件添加使用的是FormData，需要提交新的表单数据 给表单数据要用append,一项一项添加
          //所以需要使用对象循环
          this.list.description = this.editor.txt.html();
          let datas = new FormData();
          for (let i in this.list) {
            datas.append(i, this.list[i]);
          }
          addGoods(datas).then((res) => {
            if (res.code == 200) {
              this.$message.success(res.msg);
              this.getGoodsListAction();
              this.getTotalAction();
              this.cancle();
            } else {
              this.$message.error(res.msg);
            }
          });
        }
      });
    },
    //dialog的编辑
    edit() {
      this.$refs.diaform.validate((val) => {
        if (val) {
          this.list.description = this.editor.txt.html();
          let datas = new FormData();
          for (let i in this.list) {
            datas.append(i, this.list[i]);
          }
          editGoods(datas).then((res) => {
            if (res.code == 200) {
              this.$message.success(res.msg);
              this.getGoodsListAction();
              this.getTotalAction();
              this.cancle();
              // location.reload();
            } else {
              this.$message.error(res.msg);
            }
          });
        }
      });
    },
    lookup(id) {
      getGoodsOne({ id }).then((res) => {
        if (res.code == 200) {
          // console.log(res);
          // return
          this.list = res.list;
          this.list.id = id;
          this.list.specsattr = res.list.specsattr.split(",");
          //绑定属性可以回显 图片
          //回显文本编译器里面的东西
          // 
          this.menuChange(this.list.first_cateid,true);
          this.specsChange(this.list.second_cateid,true);
          this.fileList =this.list.img? [{ url: this.list.img }]:[];
        }
      });
    },
    filechange(file) {
      this.list.img = file.raw;
    }
  
  },
  mounted() {
    //页面挂载后循环数据  分类数据
    getCatelist({ pid: 0 }).then((res) => {
      if (res.code == 200) {
        this.firstarr = res.list;
      } else {
        this.$message.error(res.msg);
      }
    });
    //规格和属性数据
    specsList().then((res) => {
      if (res.code == 200) {
        this.specsarr = res.list;
      } else {
        this.$message.error(res.msg);
      }
    });
  },
};
</script>

<style lang="stylus" scoped></style>